import { ref, onMounted, reactive, watch } from 'vue'
import dayjs from 'dayjs';
import { saveItem, getItems, getItemById, updateItem, deleteItem } from '../db';
import { message } from 'ant-design-vue';
// 图像集合/
import iw_close1d3gif from '../assets/iw_close1d3.gif'

import ningdongborder from '../static/localData/ningdongborder.json'
var markers = {}
var overlays = {}
var vehicleList = {}
let catMap = ref(null)
export const selectedItemId = ref(null)

let cmarkers = []




var DIFF = 15;
// 获取不同方向颜色的车辆图标
const getRecordImageUrl = function (direction, speed, online, alarm, vehicle) {
    //       红色黄色粉色
    // 改为  黄色蓝色粉色
    // E:\phpstudy_pro\WWW\SDMP\webgis\WebRoot\map\images\car\taxi\off\0.png
    // E:\phpstudy_pro\WWW\SDMP\webgis\WebRoot\map\images\car\taxi\empty\0.png
    // E:\phpstudy_pro\WWW\SDMP\webgis\WebRoot\map\images\car\taxi\load\0.png

    // 过境橙色
    // 违停红色
    // E:\phpstudy_pro\WWW\SDMP\webgis\WebRoot\map\images\car\alarm\0.png
    // E:\phpstudy_pro\WWW\SDMP\webgis\WebRoot\map\images\car\carimages\Y2_0_0.png
    // vehicleType ['vtype3', 'vtype4', 'vtype5']
    if (!direction)
        direction = 0;
    if (!direction)
        direction = 0;
    var img = setAngleImage(direction);

    var path = "https://aimonitoring.rybsj.cn/webgis/map/images/" + 'car' + "/";
    var status = "offline";
    // if(online)
    // {
    //   if (typeof(alarm) != "undefined" && parseInt(alarm) != 0){
    //     status = "alarm";
    //     }else if(speed <= 1)
    //   {
    //       status = "parking";
    //   }else			
    //     status = "run";
    // }
    if (vehicle.vehicleType == 'vtype3') status = 'taxi/off'
    if (vehicle.vehicleType == 'vtype4') status = 'taxi/empty'
    if (vehicle.vehicleType == 'vtype5') status = 'taxi/load'
    // if (vehicle.illegalParking.show){
    //      status = 'alarm'
    // }
    // if (vehicle.viaVehicle.show){
    //      status = 'guojing'
    // }
    return path + status + "/" + img;
}// 获取不同方向颜色的车辆图标
const getRecordImageUrlMergeSame = function (vehicle, who) {
    if (!vehicle.direction)
        vehicle.direction = 0;
    if (!vehicle.direction)
        vehicle.direction = 0;
    var img = setAngleImage(vehicle.direction);

    var path = "https://aimonitoring.rybsj.cn/webgis/map/images/" + 'car' + "/";
    var status = "offline";

    if (vehicle.vehicleType == 'vtype3' && who == 'vtype3') status = 'taxi/off'
    if (vehicle.vehicleType == 'vtype4' && who == 'vtype4') status = 'taxi/empty'
    if (vehicle.vehicleType == 'vtype5' && who == 'vtype5') status = 'taxi/load'

    if (vehicle.illegalParking.show && who == 'illegalParking') {
        status = 'alarm'
    }
    if (vehicle.viaVehicle.show && who == 'viaVehicle') {
        status = 'guojing'
    }
    return path + status + "/" + img;
}
// 获取方法车辆图标路径
const setAngleImage = (angle) => {
    // document.getElementById("debugger").innerHTML += angle;
    try {
        if (angle >= (360 - DIFF) || angle <= DIFF) {
            return "0.png";
        }

        if (angle >= (90 - DIFF) && angle <= (90 + DIFF)) {
            return "90.png";
        }

        if (angle >= (180 - DIFF) && angle <= (180 + DIFF)) {
            return "180.png";
        }

        if (angle >= (270 - DIFF) && angle <= (270 + DIFF)) {
            return "270.png";
        }


        if (angle > DIFF && angle < (90 - DIFF)) {
            return "30.png";
        }

        if (angle > (90 + DIFF) && angle < (180 - DIFF)) {
            return "120.png";
        }

        if (angle > (180 + DIFF) && angle < (270 - DIFF)) {
            return "210.png";
        }

        if (angle > (270 + DIFF) && angle < (360 - DIFF)) {
            return "300.png";
        }
    } catch (e) {
        return '未知';
    }
}


var _renderClusterMarker = function (context) {
    // 聚合中点个数
    var clusterCount = context.count;
    var div = document.createElement('div');
    // 聚合点配色
    var defaultColor = [
        '204,235,197',
        '168,221,181',
        '123,204,196',
        '78,179,211',
        '43,140,190',
    ]
    if(clusterCount >= 0 && clusterCount < 10) {
        bgColor = defaultColor[0];
    } else if(clusterCount >= 10 && clusterCount < 100){
        bgColor = defaultColor[1];
    } else if(clusterCount >= 100 && clusterCount < 1000) {
        bgColor = defaultColor[2];
    } else if(clusterCount >= 1000 && clusterCount < 10000) {
        bgColor = defaultColor[3];
    } else if(clusterCount >= 10000) {
        bgColor = defaultColor[4];
    }
    div.style.backgroundColor = 'rgba(' + bgColor + ',.5)';
    var size = Math.round(25 + Math.pow(clusterCount/count, 1 / 5) * 40);
    div.style.width = div.style.height = size + 'px';
    div.style.border = 'solid 1px rgba(' + bgColor + ',1)';
    div.style.borderRadius = size / 2 + 'px';
    div.innerHTML = context.count;
    div.style.lineHeight = size + 'px';
    div.style.color = '#ffffff';
    div.style.fontSize = '12px';
    div.style.textAlign = 'center';


    

    //         markerIcon = new AMap.Marker({
    //             position: position,
    //             icon: iconpath,
    //             extData: {
    //                 id: vehicle.id,
    //                 type: 'icon',
    //                 type1: 'marker'
    //             }
    //         });
    //         context.marker = markerIcon
    
    context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
    context.marker.setContent(div);
};



// 创建窗口信息
const createInfoWindowContent = (vehicle, templateID=1) => {
    selectedItemId.value = vehicle.ID
    window.currentItem = vehicle
    
    const div = document.createElement('div');

    const closeImg = document.createElement('img');
    closeImg.className = `close_${vehicle.id} mapclose`;
    closeImg.src = iw_close1d3gif;
    closeImg.addEventListener('click', () => {
        console.log(`Close button ${vehicle.id} clicked`);
        window.bMapInfoWindow.hide()
    });

    // 创建并配置三角形 div
    const triangleDiv = document.createElement('div');
    triangleDiv.className = 'mapsanjiao';
    // if ((id+'').slice(-1) * 1 < 6) {
    //   triangleDiv.className = 'mapsanjiao red';
    // }
    
    const content = document.createElement('div');
    content.innerHTML = windowinfotext(vehicle);

    if (templateID == 2) {
        content.innerHTML = windowinfotext2(vehicle);
    }
    
    div.classList.add('modalDIV')
    div.appendChild(closeImg);
    div.appendChild(content);
    div.appendChild(triangleDiv);

    return div;
};

var windowinfotext2 = (vehicle) => {
    return `<style> .windowInfoContiner { min-width: 450px; background: #15285bad; border: 1px solid; padding: 10px; border-radius: 9px; font-size: 13px; } .windowInfoContiner > p { margin: 0px; line-height: 22px; } .windowInfoContiner > p > a { cursor: pointer; text-decoration: none; color: rgb(22, 162, 255); } .windowInfoContiner > p > span, .windowInfoContiner > p > a > span { color: rgb(136, 136, 136); } .windowInfoContiner > p > span span { color: rgb(124,150,255); } .windowInfoContiner .flex { display: flex; } .windowInfoContiner .flex span { width: 33.3333%; } .wintitle { cursor: pointer; text-decoration: none; color: rgb(22, 162, 255); }</style>
        <div class="windowInfoContiner">
            <p><a href="javascript:void(0)" class="wintitle">${vehicle.plateNo ?? ''}</a></p>		
            <p><a href="javascript:void(0)"><span>上报事件：</span>${vehicle.alarmTypeName ?? ''}</a></p>
            <p>
                <span>车辆状态：</span><span style="color: red;">${vehicle.status ? vehicle.status+' ' : ''}</span>
            </p>

            <p class="flex">
            <span style="width: 50%;">上报时间：<span>${vehicle.locationUpdateTime ??''} </span></span>
            <span style="width: 50%;">速度方向：<span>${vehicle.velocity ? vehicle.velocity : ''}</span></span>
            </p>
            
            <p><span>停车   场名称：<span>${vehicle.parkingAreaName ?? ''}</span></span></p>
            <p><span>停车场入口：<span>${vehicle.recordInName ?? ''}</span></span></p>
            <p><span>车辆类型：<span>${vehicle.carTypeName ?? ''}</span></span></p>
            
            <p class="flex">
            <span>主驾驶员：<span>${vehicle.driverName ?? ''} </span> </span>
            <span>联系电话：<span>${vehicle.telephone ?? ''}</span> </span>
            <span>短信下发：<span>是</span> </span>
            </p>
            <p class="flex">
            <span>车管姓名：<span>${vehicle.vehMan ?? ''}</span> </span>
            <span>车管电话：<span>${vehicle.vehTel ?? ''}</span> </span>
            <span>终端卡号：<span> </span> </span>
            </p>
            <p>
                <span>入场时间：<span>${vehicle.checkInTime ?? ''}</span></span>
            </p>

            
        </div>`
}
    
var windowinfotext = (vehicle) => {
    return `<style> .windowInfoContiner { min-width: 450px; background: #15285bad; border: 1px solid; padding: 10px; border-radius: 9px; font-size: 13px; } .windowInfoContiner > p { margin: 0px; line-height: 22px; } .windowInfoContiner > p > a { cursor: pointer; text-decoration: none; color: rgb(22, 162, 255); } .windowInfoContiner > p > span, .windowInfoContiner > p > a > span { color: rgb(136, 136, 136); } .windowInfoContiner > p > span span { color: rgb(124,150,255); } .windowInfoContiner .flex { display: flex; } .windowInfoContiner .flex span { width: 33.3333%; } .wintitle { cursor: pointer; text-decoration: none; color: rgb(22, 162, 255); }</style>
        <div class="windowInfoContiner">
            <p><a href="javascript:void(0)" class="wintitle">${vehicle.plateNo ?? ''}</a></p>		
            <p><a href="javascript:void(0)"><span>上报事件：</span>${vehicle.alarmTypeName ?? ''}</a></p>
            <p>
                <span>车辆状态：</span><span style="color: red;">${vehicle.status ? vehicle.status+' ' : ''}${vehicle.illegalParking.show ? '违停 ' : ''}${vehicle.viaVehicle.show ? '过境 ' : ''}</span>
            </p>

            <p class="flex">
            <span style="width: 50%;">上报时间：<span>${vehicle.locationUpdateTime ??''} </span></span>
            <span style="width: 50%;">速度方向：<span>${vehicle.velocity ? vehicle.velocity : ''}</span></span>
            </p>
            
            <p><span>上报地点：<span>${vehicle.location ?? ''}</span></span></p>
            
            <p class="flex">
            <span>主驾驶员：<span>${vehicle.driverName ?? ''} </span> </span>
            <span>联系电话：<span>${vehicle.telephone ?? ''}</span> </span>
            <span>短信下发：<span>是</span> </span>
            </p>
            <p class="flex">
            <span>车管姓名：<span>${vehicle.vehMan ?? ''}</span> </span>
            <span>车管电话：<span>${vehicle.vehTel ?? ''}</span> </span>
            <span>终端卡号：<span>41040098630 </span> </span>
            </p>

            <p><span>身份证：<span>${vehicle.identityCard ?? ''}</span></span></p>
            <p><span>刷卡时间：<span>${vehicle.cardInTime ?? ''}</span></span></p>
            <p><span>出车时间：<span>${vehicle.dispatchTime ?? ''}</span></span></p>
            <p><span>停车时长：<span>${vehicle.parkingTime ?? ''}</span></span></p>
            <p><span>离线时长：<span>${vehicle.offlineTime ?? ''}</span></span></p>
            <p><span>禁行时长：<span>${vehicle ?.illegalParking.parkingtime ?? ''}</span></span></p>
            <p><span>禁行路线：<span>${vehicle.viaVehicle.route ? vehicle.viaVehicle.route[0] + vehicle.viaVehicle.route[1] : ''}</span></span></p>
            <p><span>所属部门：<span>${vehicle.depName ?? ''}</span></span></p>
        </div>`
}
    
var _renderMarker = function(context) {
    let vehicle = context.data[0]
    let speed = 0
    if (vehicle.text) {
        speed = vehicle.text.match(/(\d+)(?=\(km\))/) ? vehicle.text.match(/(\d+)(?=\(km\))/)[0] : 0
    }
    let alarm = vehicle.alarmState != '' || vehicle.alarmState != 0
    let iconpath = getRecordImageUrl(vehicle.direction, speed, vehicle.online, alarm, vehicle);
            
    
    var content = '<div style="background-color: rgba(255,255,178,.9); height: 18px; width: 18px; border: 1px solid rgba(255,255,178,1); border-radius: 12px; box-shadow: rgba(0, 0, 0, 1) 0px 0px 3px;"></div>';
    var offset = new AMap.Pixel(16, -45)
    context.marker.setContent(content)

    // 聚合, 现在不使用, 使用的时候setIcon注释setContent
    // context.marker.setIcon(iconpath);

    // context.marker.on('click', () => {
    //     var marker,
    //     content = createInfoWindowContent(vehicle),
    //     position = [vehicle.longitude,vehicle.latitude]
    //     if (!window.bMapInfoWindow) {

    //         marker = new AMap.InfoWindow({
    //             isCustom: true,  //使用自定义窗体
    //             position: position,
    //             offset: new AMap.Pixel(16, -45),
    //             content: content,
    //             extData: {
    //                 id: vehicle.id,
    //                 type: 'modal',
    //                 type1: 'marker'
    //             }
    //         });
    //         window.bMapInfoWindow = marker
            
    //         catMap.add(marker);
    //         marker.hide()
    //     } else {
    //         window.bMapInfoWindow.setContent(content)
    //         window.bMapInfoWindow.setPosition(position)
    //         window.bMapInfoWindow.show()
    //     }
        
    //     // createCustomMarker(createInfoWindowContent(vehicle), position, vehicle, true, true);
    //     window.bMapInfoWindow.show()
    //     window.bMapInfoWindow.setContent(content)
    //     window.bMapInfoWindow.setPosition(position)
    //     catMap.setCenter(position)
    //     catMap.panBy(0, 100);
    // })
    
    // if (!cmarkers[vehicle.id + '_icon'])
    //     cmarkers[vehicle.id + '_icon'] = context.marker
}

var count
var bgColor


export function useMap(mapContainer, markers, overlays, pointsList) {
    const mapInstance = ref(null)
    markers = markers
    overlays = overlays
    
    onMounted(() => {
        mapInstance.value = new AMap.Map(mapContainer.value, {
            // pitch: 65,
            // rotation: 45,
            // viewMode: '3D',//开启3D视图,默认为关闭
            animateEnable: false,// 动画
            zoom: 12,
            center: [106.653651, 38.099586], // 设置中心点
        })
        catMap = mapInstance.value
        let marker
        
        if (!window.bMapInfoWindow) {
            marker = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                position: [106.653651, 38.099586],
                offset: new AMap.Pixel(16, -5),
                content: ''
            });
            window.bMapInfoWindow = marker
            
            catMap.add(marker);
            marker.hide()
        }
        
        // 设置地图样式以隐藏地名
        // const mapStyle = {
        //   features: ['road', 'building', 'water', 'land'], // 仅显示道路、建筑物、水系和土地
        // };

        // 点聚合, 暂不使用
        // console.log(pointsList,'pointsList');
        // var points = [
        //     { weight: 8, lnglat:["116.408032","39.909729"], "name": '北京'},
        //     { weight: 8, lnglat:["121.461743","31.231584"], "name": '上海'},
        //     { weight: 8, lnglat:["113.265942","23.08983"], "name": '广州'},
        //     { weight: 8, lnglat:["104.059399","30.562253"], "name": '成都'},
        //     { weight: 1, lnglat: ["108.939621", "34.343147"] },
        //     { weight: 1, lnglat: ["112.985037", "23.15046"] },
        // ]
        // count = points.length
        // new AMap.MarkerCluster(catMap, pointsList.value, {
        //     gridSize: 60, // 聚合网格像素大小
        //     renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
        //     renderMarker: _renderMarker,   // 自定义非聚合点样式
        // });

        // watch(pointsList, (points) => {
        //     count = points.length;
        //     var cluster = new AMap.MarkerCluster(catMap, points, {
        //         gridSize: 60, // 聚合网格像素大小
        //         renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
        //         renderMarker: _renderMarker,   // 自定义非聚合点样式
        //     });
        //   });

        const geojson = new AMap.GeoJSON({
            geoJSON: ningdongborder,
            getPolygon: function (geojson, lnglats) {
                return new AMap.Polygon({
                    path: lnglats,
                    strokeColor: '#FF33FF',
                    strokeWeight: 2,
                    fillOpacity: .3,
                    fillColor: '#1791fc',
                    zIndex: 49
                });
            }
        });
        // catMap.add(geojson);

        // 获取 GeoJSON 对象的所有多边形
        var polygons = geojson.getOverlays();

        // 计算所有多边形的边界并获取中心点
        if (polygons.length > 0) {
            var bounds = polygons[0].getBounds();
            for (var i = 1; i < polygons.length; i++) {
                bounds.extend(polygons[i].getBounds());
            }
            var center = bounds.getCenter();

        }

        // 监听地图缩放事件
        catMap.on('zoomchange', function () {
            var currentZoom = catMap.getZoom();
            if (currentZoom >= 13) {
                geojson.hide();
            } else {
                geojson.show();
            }
        });

        // 初始化时根据当前缩放级别设置显示状态
        if (catMap.getZoom() >= 13) {
            geojson.hide();
        } else {
            geojson.show();
        }

        catMap.on('mapmove', function (e) {
            if (e.target && e.target.getExtData && e.target.getExtData().type1 === 'marker') {
                // 如果是 marker，则阻止地图移动
                e.preventDefault(); // 阻止默认行为
                catMap.panBy(0, 0); // 停止地图移动
            } else {
                // 否则继续移动地图
                // console.info(e.target);
            }
        });



        // map.setFeatures(mapStyle.features); // 设置显示的要素
        var styleName = "amap://styles/darkblue";
        styleName = "amap://styles/blue";
        catMap.setMapStyle(styleName);


        var driving = new AMap.Driving({
            map: catMap,
            // panel: "panel"
        });
        var startLngLat, endLngLat;
        var clickCount = 0;

        // 路线规划, 获取路线信息
        // if (document.getElementById('planRoute'))
        //     document.getElementById('planRoute').onclick = function () {
        //         clickCount = 0;
        //         startLngLat = null;
        //         endLngLat = null;
        //         catMap.on('click', mapClickHandler);
        //         message.info('请在地图上点击选择起点和终点');
        //     };
        // document.getElementById('planRoute').onclick = function() {

        // }

        function mapClickHandler(e) {
            clickCount++;
            let marker
            if (clickCount === 1) {
                startLngLat = e.lnglat;
                marker = new AMap.Marker({
                    position: startLngLat,
                    map: catMap,
                    label: {
                        content: '起点',
                        offset: new AMap.Pixel(20, 20)
                    },
                    extData: {
                        type1: 'marker'
                    }
                });
                console.log('起点设置成功:', startLngLat);
            } else if (clickCount === 2) {
                endLngLat = e.lnglat;
                marker = new AMap.Marker({
                    position: endLngLat,
                    map: catMap,
                    label: {
                        content: '终点',
                        offset: new AMap.Pixel(20, 20)
                    },
                    extData: {
                        type1: 'marker'
                    }
                });
                console.log('终点设置成功:', endLngLat);
                catMap.off('click', mapClickHandler); // 停止监听点击事件

                driving.search(startLngLat, endLngLat, function (status, result) {
                    if (status === 'complete') {
                        console.log('绘制驾车路线完成', result);
                        catMap.setCenter([startLngLat.lng, startLngLat.lat]);
                    } else {
                        console.error('获取驾车数据失败：' + result);
                    }
                });
            }

            // 阻止标记和信息窗体拖动时地图移动
            function preventMapMove(e) {
                e.preventDefault();
            }

            if (marker) {

                // 为标记添加事件处理程序
                marker.on('mousedown', preventMapMove);
                marker.on('mouseup', preventMapMove);
                marker.on('touchstart', preventMapMove);
                marker.on('touchend', preventMapMove);
            }

        }

        
        
    })


    /**
     * 创建自定义点标记
     * 
     * @param content 窗口信息内容
     * @param modalShow 是否显示窗口
     */
    const createCustomMarker = (content, position, vehicle, modalShow = false, multiple = false) => {
        let markerIcon
        // 在多选相同类型车辆时,这里不要重复设置窗口内容, 甚至不用设置, 设置不用执行这里任何逻辑
        if (!multiple) {
            window.bMapInfoWindow.setContent(content)
            window.bMapInfoWindow.setPosition(position)
            if (modalShow)
                window.bMapInfoWindow.show()
        }
        
        if (!markers[vehicle.id + '_icon']) {
            let speed = 0
            if (vehicle.text) {
                speed = vehicle.text.match(/(\d+)(?=\(km\))/) ? vehicle.text.match(/(\d+)(?=\(km\))/)[0] : 0
            }
            let alarm = vehicle.alarmState != '' || vehicle.alarmState != 0
            let iconpath = getRecordImageUrl(vehicle.direction, speed, vehicle.online, alarm, vehicle);

            markerIcon = new AMap.Marker({
                position: position,
                // icon: iconpath,
                content:`
                <div><img class="markerlnglat" src="${iconpath}"><span class="marker hiding">${vehicle.plateNo}</span></div>
                `
            });

            markerIcon.on('click', () => {
                // 点击车牌只显示一个窗口
                window.bMapInfoWindow.show()
                window.bMapInfoWindow.setContent(content)
                window.bMapInfoWindow.setPosition(position)
                catMap.setCenter(position)
                catMap.panBy(0, 100);
            })

            markers[vehicle.id + '_icon'] = markerIcon
            catMap.add(markerIcon);
        }
        markers[vehicle.id + '_icon'].setPosition(position)
        markers[vehicle.id + '_icon'].show()

    };
    // 修改icon
    const updateCustomMarker = (vehicle, who) => {
        let iconpath = getRecordImageUrlMergeSame(vehicle, who);
        if (markers[vehicle.id + '_icon']) {
            // markers[vehicle.id + '_icon'].setIcon(iconpath)
            let content = markers[vehicle.id + '_icon'].getContent()
            markers[vehicle.id + '_icon'].setContent(content.replace(/src=".*?"/,"src=\""+iconpath+"\""))
        }
    };

    const toDetail = async (vehicle, callback, templateID) => {

        // 点击车牌只显示一个窗口
        Object.values(markers).forEach(marker => {
            marker.hide()
        })

        if (typeof callback == 'function') {
            callback(vehicle)
        } else {
            let position = [vehicle.longitude, vehicle.latitude]
            // 点击车辆数的车辆定位车辆并打开窗口
            createCustomMarker(createInfoWindowContent(vehicle, templateID), position, vehicle, true, false);
            // map.setZoomAndCenter(18,position)
            catMap.setCenter(position)
            if (window.bMapInfoWindow.getIsOpen()) {
                catMap.panBy(0, 100);
            }
        }
    }

    return { mapInstance, createCustomMarker, updateCustomMarker, createInfoWindowContent, toDetail }
}
